Chapter 12: Regression Foundations, KNN, and Regression Trees
Introduction
This chapter marks the transition from classification to regression problems.
Classification vs. Regression:
Aspect
Classification
Regression
Output Type
Discrete labels
Continuous values
Examples
Spam detection, image classification
House price prediction, temperature forecasting
Loss Functions
Cross-entropy, Gini impurity
MSE, MAE, RMSE
Evaluation Metrics
Accuracy, Precision, Recall, F1, AUC-ROC
RMSE, MAE, R²
The key distinction is therefore the type of target variable being predicted.
This lecture covers:
Introduction to regression problems
Evaluation metrics for regression
K-Nearest Neighbors (KNN) for regression
Regression Trees (Decision Trees for regression)
Comparison of regression algorithms
Real-world Regression Examples:
Predicting house prices from size, location, and features
Estimating rainfall from weather sensor data
Forecasting stock prices or energy demand
Predicting student GPA from study hours and attendance
Estimating patient recovery time from medical measurements
These examples illustrate that regression is useful whenever the target is a numerical quantity.
2. Theory
2.1 From Classification to Regression
While classification and regression are different types of prediction problems, they follow a similar overall ML pipeline:
Data collection
Data preprocessing
Handle missing values, outliers
Feature scaling (critical for models using gradient descent)
Encoding (relevant for mixed features)
Train-test split (or train-val-test)
Model training
Choose algorithm (e.g., linear regression, regression trees, gradient boosting)
Optimize using regression-specific loss (e.g., MSE, MAE)
Evaluation
Use regression metrics: RMSE, MAE, R²
Not classification metrics: accuracy, F1-score, AUC-ROC
2.2 Evaluation: How Do We Measure Regression Performance?
A regression model is rarely exactly right. Instead of counting correct predictions, we measure how far the predictions are from the true values. The three standard metrics differ in how they treat large errors.
Unlike classification, which commonly uses metrics such as accuracy and F1-score, regression requires different evaluation metrics:
Use case: When outliers are present and you want a robust metric
Choosing Between MSE, RMSE, and MAE:
Metric
Sensitive to Outliers
Interpretable Units
Differentiable
MSE
✅ Yes (heavily)
❌ No (squared units)
✅ Yes
RMSE
✅ Yes (heavily)
✅ Yes (original units)
❌ No (due to square root)
MAE
❌ No (robust)
✅ Yes (original units)
❌ No (due to absolute value)
The choice of metric depends on whether large errors should be penalized strongly or treated more evenly.
2.6 Regression Algorithms – Course Roadmap
This course will cover several regression algorithms, including:
K-Nearest Neighbors (KNN) Regressor
Non-parametric, instance-based
Simple extension from KNN classification
Regression Trees (Decision Trees)
Non-parametric, rule-based
Splits to minimize MSE
Ordinary Least Squares (OLS) Regression
Parametric, linear model
Closed-form solution or gradient descent
Polynomial Regression
Extending OLS for non-linear relationships
Feature engineering approach
Regularized Regression (Ridge & Lasso)
OLS with shrinkage/penalty
Prevents overfitting, automatic feature selection
Gradient Boosting for Regression
Ensemble method (combines multiple trees)
State-of-the-art performance
2.7 K-Nearest Neighbors (KNN) Regressor
Like KNN classification, KNN regression identifies the nearest neighbors of a query point. Instead of assigning a class label, however, it predicts a continuous value by averaging the target values of those neighbors.
How KNN Regression Works:
For a given query point, identify the k-nearest neighbors.
Compute the average (or weighted average) of their target values to get the prediction
Typically use Euclidean distance, although other metrics such as Manhattan distance can also be used to find the nearest neighbors
With weighted KNN, closer neighbors are given higher weights in the averaging process, so they have a greater influence on the prediction
Thus, KNN regression bases each prediction on the local neighborhood around the query point.
Characteristics:
Computationally expensive: Prediction can become expensive with large datasets, especially as the number of features grows
Sensitive to the choice of k: A small k can lead to noisy predictions, while a large k can oversmooth the predictions
Sensitive to distance metric: Different distance metrics can give different results
Works well for non-linear relationships: KNN can work well when the data contains local patterns rather than a single global trend
No training phase: KNN is a lazy learner; it stores the training data and performs the main computation when making predictions
2.8 KNN Regression Example
Consider a small dataset with TV, Radio, and Newspaper advertising budgets, where Sales is the target variable:
#
TV
Radio
Newspaper
Sales
R1
230.1
37.8
69.2
?
R2
44.5
39.3
45.1
10.4
R3
17.2
45.9
69.3
9.3
R4
151.5
41.3
58.5
18.5
R5
180.8
10.8
58.4
12.9
R6
8.7
48.9
75
7.2
Example predictions: Using the nearest neighbors identified for each value of K, we obtain the following predictions:
When K = 1: Nearest neighbor is R4, hence predicted value = 18.5
When K = 3: Nearest neighbors are R4, R5, and R6, hence predicted value = (18.5 + 12.9 + 7.2)/3 = 12.87
When K = 5: Predicted value = 11.66
s*
2.9 Regression Tree
Decision trees can also be used when the response variable is numerical. Regression trees operate much like classification trees, but the target, leaf prediction, and splitting criterion are different:
Regression Trees vs Classification Trees:
Aspect
Classification Trees
Regression Trees
Target Variable
Categorical
Continuous
Leaf Node Value
Majority class (voting)
Average of training data in that leaf
Impurity Measure
Gini impurity, Entropy
Sum of squared deviations from the mean
Splitting Criterion
Maximize information gain
Minimize MSE (or variance)
The main change from classification to regression is how leaf predictions and split quality are defined.
Key Insight: In a regression tree, the value of a leaf node is the average of the training targets that fall into that leaf. A typical impurity measure is the sum of the squared deviations from the leaf mean.
Important Notes:
Data requirements: As with other data-driven methods, trees require large amounts of data
Overfitting: Regression trees are prone to overfitting (we'll discuss this more later)
Interpretability: One advantage of regression trees is that they are highly interpretable
2.10 Regression Tree Example
Consider a dataset for predicting the number of golf players from weather conditions:
Day
Outlook
Temp.
Humidity
Wind
Golf Players
1
Sunny
Hot
High
Weak
25
2
Sunny
Hot
High
Strong
30
3
Overcast
Hot
High
Weak
46
4
Rain
Mild
High
Weak
45
5
Rain
Cool
Normal
Weak
52
6
Rain
Cool
Normal
Strong
23
7
Overcast
Cool
Normal
Strong
43
8
Sunny
Mild
High
Weak
35
9
Sunny
Cool
Normal
Weak
38
10
Rain
Mild
Normal
Weak
46
11
Sunny
Mild
Normal
Strong
48
12
Overcast
Mild
High
Strong
52
13
Overcast
Hot
Normal
Weak
44
14
Rain
Mild
High
Strong
30
Now consider the same dataset again, but with Temperature represented as a numeric predictor:
Day
Outlook
Temp.
Humidity
Wind
Golf Players
1
Sunny
42
High
Weak
25
2
Sunny
38
High
Strong
30
3
Overcast
40
High
Weak
46
4
Rain
32
High
Weak
45
5
Rain
12
Normal
Weak
52
6
Rain
14
Normal
Strong
23
7
Overcast
15
Normal
Strong
43
8
Sunny
28
High
Weak
35
9
Sunny
10
Normal
Weak
38
10
Rain
24
Normal
Weak
46
11
Sunny
22
Normal
Strong
48
12
Overcast
26
High
Strong
52
13
Overcast
36
Normal
Weak
44
14
Rain
30
High
Strong
30
Effect of Tree Depth:
With max_depth=2: The tree makes only a few cuts, resulting in a simpler, "step-like" prediction that may not capture finer variations in the data
With max_depth=3: More splits lead to a more complex tree that can better adapt to variations in the data
Interpretability: RMSE is easier to interpret because it's in the same units as the target variable (2.5 vs 1.58, where 1.58 is more meaningful)
Problem 2: MAE vs MSE
Given two models with the following errors on a test set:
Model A: Errors = [-3, -2, -1, 0, 1, 2, 3]
Model B: Errors = [-5, -1, -1, 0, 1, 1, 5]
Tasks:
Calculate MAE for both models
Calculate MSE for both models
Which model performs better according to MAE?
Which model performs better according to MSE?
Which metric do you think is more appropriate here and why?
Solution:
MAE:
Model A: (3+2+1+0+1+2+3)/7 = 12/7 ≈ 1.71
Model B: (5+1+1+0+1+1+5)/7 = 14/7 = 2.0
MSE:
Model A: (9+4+1+0+1+4+9)/7 = 28/7 = 4.0
Model B: (25+1+1+0+1+1+25)/7 = 54/7 ≈ 7.71
MAE winner: Model A (1.71 < 2.0)
MSE winner: Model A (4.0 < 7.71)
Appropriate metric: Both metrics agree that Model A is better. However, MSE penalizes Model B more heavily for its large errors (-5 and 5), which might be desirable if large errors are particularly bad. MAE is more robust to outliers.
Problem 3: KNN Regression Prediction
Given the following training data (x, y):
(1, 3), (2, 5), (3, 7), (4, 9), (5, 11)
Query point: x = 3.5
Tasks:
What is the prediction when K=1?
What is the prediction when K=2?
What is the prediction when K=3?
As K increases, what happens to the prediction?
Solution:
K=1: Nearest neighbor is (3, 7) or (4, 9). Assuming Euclidean distance, both are equally close (distance=0.5). Typically, we'd pick the first one: Prediction = 7
As K increases: The prediction becomes more smoothed and approaches the average of all y values (7). With K=5, prediction = (3+5+7+9+11)/5 = 7.
Problem 4: Regression Tree Splitting
Consider a simple dataset for predicting house prices based on square footage:
Square Feet
Price ($1000s)
1000
200
1200
220
1500
250
1800
300
2000
320
Task: If we're building a regression tree with max_depth=1 (one split), where would be the optimal split point to minimize MSE? Calculate the MSE for splits at 1300, 1400, 1600, and 1700 square feet.
Solution:
For each potential split, we calculate the MSE of the predictions:
Split at 1300:
Left (≤1300): 1000(200), 1200(220) → mean = 210
Right (>1300): 1500(250), 1800(300), 2000(320) → mean = 290
Optimal split: At 1600 square feet with MSE = 292 (lowest MSE)
Problem 5: Choosing Evaluation Metric
You are building a model to predict house prices, and your dataset contains some outliers (very expensive houses that are unusual for their size).
Tasks:
Which evaluation metric would you choose: MSE, RMSE, or MAE?
Why is this metric more appropriate?
If you want to heavily penalize large errors (e.g., underestimating the price of an expensive house by a lot), which metric would you choose?
Solution:
Recommended metric: MAE (Mean Absolute Error)
Reason: MAE is more robust to outliers. Since the dataset contains outliers (very expensive houses), MSE and RMSE would be heavily influenced by these extreme values, giving a distorted view of typical model performance. MAE treats all errors equally, regardless of their magnitude.
For penalizing large errors: MSE or RMSE. Both heavily penalize large errors due to the squaring operation. RMSE is often preferred because it's in the same units as the target variable, making it more interpretable.
6. Interactive Quiz
Answer all 5 questions. Click an option for instant feedback.
Distance metric: Typically Euclidean, but can use others (Manhattan, etc.)
Strengths: Simple, works well for non-linear relationships with local patterns
Weaknesses: Computationally expensive, sensitive to choice of k and distance metric
Regression Trees:
Non-parametric: Makes no assumptions about the functional form
Rule-based: Creates a series of if-then rules based on feature thresholds
Leaf value: Average of training data in that leaf (unlike classification trees which use majority voting)
Splitting criterion: Minimizes MSE (or variance) of the resulting subsets
Strengths: Highly interpretable, can capture non-linear relationships, handles both numerical and categorical features
Weaknesses: Prone to overfitting, can be unstable (small data changes can lead to different trees)
General Insights:
Metric selection: Choose based on your priorities: MSE/RMSE for penalizing large errors, MAE for robustness to outliers
Model selection: KNN for local patterns, Regression Trees for interpretable non-linear relationships
Overfitting: Always a concern with flexible models like regression trees; use regularization or pruning
Feature importance: Regression trees naturally provide feature importance scores
8. Common Pitfalls
️ Evaluation Metrics:
Using classification metrics: Never use accuracy, precision, recall, or F1-score for regression problems
Ignoring units: MSE has squared units, which can be misleading. RMSE is often more interpretable
Over-reliance on a single metric: Different metrics tell different stories. Use multiple metrics for a complete picture
Comparing metrics across scales: Metrics like MSE/RMSE/MAE are scale-dependent. Standardize or use relative metrics when comparing across different datasets
️ KNN Regressor:
Choosing k: Too small k leads to noisy, overfit predictions; too large k leads to oversmoothed, high-bias predictions
Distance metric: Euclidean distance assumes spherical neighborhoods, which may not be appropriate for all data distributions
Feature scaling: Features must be scaled (standardized/normalized) when using Euclidean distance, otherwise features with larger scales will dominate
Computational cost: KNN can be slow for large datasets, especially in high dimensions
Curse of dimensionality: KNN performance degrades in high-dimensional spaces as all points become equally distant
️ Regression Trees:
Overfitting: Regression trees can easily overfit the training data, creating trees that are too complex
No pruning: Without regularization (e.g., min_samples_leaf, max_depth), trees will grow until each leaf is pure or contains min_samples_split
Unstable: Small changes in the data can lead to very different tree structures
Biased towards dominant classes: In regions with few training samples, predictions may be unreliable
Extrapolation: Regression trees perform poorly on data outside the range of the training data
Feature importance bias: Trees tend to favor features with more possible split points (e.g., continuous over categorical)
️ General:
Data leakage: Ensure that preprocessing (scaling for KNN) is done correctly within cross-validation folds
Ignoring assumptions: While tree-based methods make few assumptions, KNN assumes that nearby points have similar target values
Target variable distribution: Both KNN and regression trees assume that the target variable is roughly continuous in the input space